import time
import os
from flask import Flask, jsonify, request
import pymysql
from flask_cors import CORS
import bcrypt
import jwt
from datetime import datetime
from config.config import DB_CONFIG
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
import random
from functools import wraps
from flask import request, jsonify


def require_api_key(view_function):
    @wraps(view_function)
    def decorated_function(*args, **kwargs):
        if request.headers.get('X-API-KEY') == 'zhejiangdongfangzhiyejishuxueyuan':
            return view_function(*args, **kwargs)
        else:
            return jsonify({'data': {'code': 403, 'msg': '无效的API密钥'}})

    return decorated_function


app = Flask(__name__)

CORS(app)


# 创建数据库连接
def get_db_connection():
    return pymysql.connect(**DB_CONFIG)


def login():
    data = request.get_json()
    if not data or 'mail' not in data or not data['mail'].strip() or 'password' not in data or not data['password'].strip():
        return jsonify({'data': {'code': 400, 'msg': '邮箱或密码为空'}})
    conn = get_db_connection()
    cursor = conn.cursor()
    mail = data['mail']
    password = data['password'].encode('utf-8')
    cursor.execute('SELECT `username`, `password` FROM `userinfo` WHERE `mail` = %s', (mail,))
    result = cursor.fetchone()
    cursor.close()
    conn.close()
    if result is None:
        return jsonify({'data': {'code': 400, 'msg': '邮箱不存在'}})
    username, stored_password = result[0], result[1].encode('utf-8')
    if bcrypt.checkpw(password, stored_password):
        current_time = time.time()
        expire_time = current_time + 24 * 60 * 60 * 7
        random_salt = os.urandom(512).hex()  # 生成一个随机的16字节的盐，并转换为十六进制字符串
        token_payload = {
            'username': username,  # 将用户名添加到JWT的payload中。这样，当你验证JWT时，你可以知道这个JWT是哪个用户的。
            'iat': current_time,  # 将当前时间戳添加到JWT的payload中，作为JWT的"iat"（Issued At）声明。这个声明表示JWT何时被创建。
            'exp': expire_time,  # 将过期时间戳添加到JWT的payload中，作为JWT的"exp"（Expiration Time）声明。这个声明表示JWT何时过期。
            'salt': random_salt,  # 添加盐到token中
            "intercom_hash": "0bae40e8b3cf95610b08c697120362e7f39b54bf883a6d2cb875534fcd6e0f3b"
            # 添加intercom_hash到token中
        }
        token = jwt.encode(token_payload, 'hongxichina', algorithm='HS256')
        return jsonify({'data': {'code': 200, 'msg': '登录成功', 'username': username, 'token': token}})
    else:
        return jsonify({'data': {'code': 400, 'msg': '密码错误'}})

def set_token():
    data = request.get_json()
    if not data or 'username' not in data or not data['username'].strip() or 'token' not in data or not data[
        'token'].strip():
        return jsonify({'data': {'code': 400, 'msg': '用户名或token为空'}})
    conn = get_db_connection()
    cursor = conn.cursor()
    username = data['username']
    token = data['token']
    cursor.execute("INSERT INTO `token` (`username`, `token`) VALUES (%s, %s)",
                   (username, token))
    conn.commit()
    cursor.close()
    conn.close()
    return jsonify({'data': {'code': 200, 'msg': 'Token设置成功'}})


def check_token():
    username = request.args.get('username')
    token = request.args.get('token')

    if not username or not token:
        return jsonify({'data': {'code': 400, 'msg': '用户名或token为空'}})

    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username,))
    results = cursor.fetchall()
    cursor.close()
    conn.close()

    if not results:
        return jsonify({'data': {'code': 400, 'msg': '用户名不存在'}})

    for result in results:
        stored_token = result[0]
        if stored_token == token:
            return jsonify({'data': {'code': 200, 'msg': 'Token验证成功'}})

    return jsonify({'data': {'code': 400, 'msg': 'Token验证失败'}})


def logon():
    data = request.get_json()
    if not data or 'username' not in data or not data['username'].strip() or 'password' not in data or not data[
        'password'].strip() or 'mail' not in data or not data['mail'].strip() or 'phone' not in data or not data[
        'phone'].strip() or 'mail_code' not in data or not data['mail_code'].strip():
        return jsonify({'data': {'code': 400, 'msg': '用户名、密码、邮箱、手机号或验证码为空'}})
    conn = get_db_connection()
    cursor = conn.cursor()
    username = data['username']
    password = data['password']
    mail = data['mail']
    phone = data['phone']
    mail_code = data['mail_code']
    # 验证邮箱验证码
    cursor.execute('SELECT `mail_code` FROM `mail_code` WHERE `mail` = %s ORDER BY `date_time` DESC LIMIT 1', (mail,))
    result = cursor.fetchone()
    if result is None or str(result[0]) != str(mail_code):
        return jsonify({'data': {'code': 400, 'msg': '验证码错误'}})
    # 其他代码...
    if len(phone) != 11 or not phone.isdigit():
        return jsonify({'data': {'code': 400, 'msg': '手机号必须为11位数字'}})
    cursor.execute('SELECT `username` FROM `userinfo` WHERE `username` = %s OR `mail` = %s OR `phone` = %s',
                   (username, mail, phone))
    if cursor.fetchone() is not None:
        cursor.close()
        conn.close()
        return jsonify({'data': {'code': 400, 'msg': '用户名、邮箱或手机号已存在'}})
    hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
    register_time = datetime.now()
    cursor.execute(
        "INSERT INTO `userinfo` (`username`, `password`, `register_time`,`Credits`, `mail`, `phone`,`img`) VALUES (%s, %s, %s,80,%s,%s,'/static/images/userimg/default.png')",
        (username, hashed_password, register_time, mail, phone))
    conn.commit()
    cursor.close()
    conn.close()
    return jsonify({'data': {'code': 200, 'msg': '注册成功'}})


# 发件人邮箱账号和密码
my_sender = '19817566936@163.com'
my_pass = 'RSTWGECWFLRWFXEE'


def send_mail_code():
    data = request.get_json()
    if not data or 'mail' not in data or not data['mail'].strip():
        return jsonify({'data': {'code': 400, 'msg': '邮箱为空'}})
    mail = data['mail']
    # 生成随机验证码
    mail_code = str(random.randint(1, 9)) + ''.join([str(random.randint(0, 9)) for _ in range(5)])    # 邮件内容和标题
    mail_msg = """
    <p>尊敬的用户，您好！</p>
    <p>您的邮箱验证码为：<strong style="color: red;">{}</strong>，请在5分钟内输入，不要泄露给他人。</p>
    <p>如非本人操作，请忽略此邮件。</p>
    <p>博奇科创祝您生活愉快！</p>
    """.format(mail_code)
    # 创建邮件实例
    msg = MIMEText(mail_msg, 'html', 'utf-8')
    msg['From'] = formataddr(["博奇科创", my_sender])
    msg['To'] = formataddr(["收件人名称", mail])
    msg['Subject'] = "邮箱验证码"
    # 发送邮件
    try:
        server = smtplib.SMTP_SSL("smtp.163.com", 465)
        server.login(my_sender, my_pass)
        server.sendmail(my_sender, [mail, ], msg.as_string())
    except smtplib.SMTPException as e:
        return jsonify({'data': {'code': 500, 'msg': '邮件发送失败', 'error': str(e)}})
    finally:
        server.quit()
    # 将验证码存储到数据库
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("INSERT INTO `mail_code` (`mail`, `mail_code`, `date_time`) VALUES (%s, %s, NOW())",
                   (mail, mail_code))
    conn.commit()
    cursor.close()
    conn.close()
    return jsonify({'data': {'code': 200, 'msg': '邮件发送成功'}})


def check_mail():
    data = request.get_json()
    if not data or 'mail' not in data or not data['mail'].strip():
        return jsonify({'data': {'code': 400, 'msg': '邮箱为空'}})
    mail = data['mail']
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute('SELECT `mail` FROM `userinfo` WHERE `mail` = %s', (mail,))
    result = cursor.fetchone()
    cursor.close()
    conn.close()
    if result is not None:
        return jsonify({'data': {'code': 400, 'msg': '邮箱已被注册'}})
    else:
        return jsonify({'data': {'code': 200, 'msg': '邮箱未被注册'}})

def check_username():
    data = request.get_json()
    if not data or 'username' not in data or not data['username'].strip():
        return jsonify({'data': {'code': 400, 'msg': '用户名为空'}})
    username = data['username']
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute('SELECT `username` FROM `userinfo` WHERE `username` = %s', (username,))
    result = cursor.fetchone()
    cursor.close()
    conn.close()
    if result is not None:
        return jsonify({'data': {'code': 400, 'msg': '用户名已存在'}})
    else:
        return jsonify({'data': {'code': 200, 'msg': '用户名未被注册'}})

class Login_Logon:
    def __init__(self, app):
        self.app = app
        self.app.add_url_rule('/api/logon', view_func=logon, methods=['POST'])
        self.app.add_url_rule('/api/login', view_func=login, methods=['POST'])
        app.add_url_rule('/api/check_username', view_func=check_username, methods=['POST'])
        self.app.add_url_rule('/api/set_token', view_func=set_token, methods=['POST'])
        self.app.add_url_rule('/api/send_mail_code', view_func=send_mail_code, methods=['POST'])
        self.app.add_url_rule('/api/check_mail', view_func=check_mail, methods=['POST'])
        self.app.add_url_rule('/api/check_token/fdgasfghjsadfjasifguasncsadfgsayuifcsdabvsadfbfsadvjckav',
                              view_func=check_token, methods=['GET'])
